package com.feiyuan.movie.webmagic.eightens;

import com.alibaba.fastjson.JSONObject;
import com.feiyuan.common.utils.HttpClientUtils;
import com.feiyuan.movie.vo.WebMovieVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

/**
 * 播放视频时视频的url
 */
public class PlayMovieUrlProcessor implements PageProcessor {

    private Logger logger = LoggerFactory.getLogger(PlayMovieUrlProcessor.class);

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    @Override
    public void process(Page page) {
        List<String> all = page.getHtml().xpath("//script").all();
        all.forEach(item -> {
            if (item.contains("var player_aaaa=")) {
//                System.out.println(item);
                String aaa = item.replace("<script type=\"text/javascript\">var player_aaaa=", "").replace("</script>", "");
//                System.out.println(aaa);
                WebMovieVO webMovieVO = JSONObject.parseObject(aaa, WebMovieVO.class);
//                System.out.println(webMovieVO);
                String url = webMovieVO.getUrl();
                String bbb = url.replace("index.m3u8", "");
                String str = HttpClientUtils.doHttpGet(url, null, null);
                logger.info("===========" + str);
                str = str.replace("#EXTM3U", "").replace("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=132,RESOLUTION=1280x536", "").replaceAll("\\s+", "");
                webMovieVO.setUrl(bbb + str);
                logger.info("this movie is:{}", webMovieVO);
                page.putField("webMovie", webMovieVO);
            }
        });
    }

    @Override
    public Site getSite() {
        return site;
    }
}
